package com.zhanghp.class014;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author zhanghp
 * @since 2024/2/27 14:53
 */
public class ConvertQueueAndStack {

    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);
        myQueue.push(4);
        while (!myQueue.empty()) {
            System.out.println(myQueue.pop());

        }

    }

    // 测试链接 : https://leetcode.cn/problems/implement-queue-using-stacks/
    static class MyQueue {

        public Stack<Integer> in;
        public Stack<Integer> out;

        public MyQueue() {
            this.in =  new Stack<>();
            this.out = new Stack<>();
        }

        public void inToOut() {
            if (out.isEmpty()) {
                while (!in.isEmpty()) {
                    out.push(in.pop());
                }
            }
        }

        public void push(int x) {
            in.push(x);
            inToOut();
        }

        public int pop() {
            inToOut();
            return out.pop();
        }

        public int peek() {
            inToOut();
            return out.peek();
        }

        public boolean empty() {
            inToOut();
            return out.isEmpty();
        }
    }

    // 测试链接 : https://leetcode.cn/problems/implement-stack-using-queues/
    static class MyStack {
        public Queue<Integer> queue;

        public MyStack() {
            this.queue = new LinkedList<>();
        }

        public void push(int x) {
            int n = queue.size();
            queue.offer(x);
            for (int i = 0; i < n; i++) {
                queue.offer(queue.poll());
            }
        }

        public int pop() {
            return queue.poll();
        }

        public int top() {
            return queue.peek();
        }

        public boolean empty() {
            return queue.isEmpty();
        }
    }
}
